package com.jd.user.service.impl;

import com.jd.basic.exception.BusinessException;
import com.jd.basic.util.MD5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.user.domain.Logininfo;
import com.jd.user.domain.User;
import com.jd.user.dto.UserDto;
import com.jd.user.mapper.LogininfoMapper;
import com.jd.user.mapper.UserMapper;
import com.jd.user.service.UserService;
import com.jd.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public void emailRegister(UserDto userDto) {
        String email = userDto.getEmail();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        // 空值校验
        if (StringUtils.isEmpty(email)) {
            throw new BusinessException("邮箱不能为空哦！");
        }
        if (StringUtils.isEmpty(pwd)) {
            throw new BusinessException("密码不能为空哦！");
        }
        if (StringUtils.isEmpty(rePwd)) {
            throw new BusinessException("确认密码不能为空哦！");
        }
        // 校验密码是否相同
        if (!pwd.equals(rePwd)) {
            throw new BusinessException("两次密码不一致哦！");
        }

        User uu = userMapper.loadByEmail(email);
        if (uu!=null) {
            throw new BusinessException("邮箱已经被注册过了，请去登录");
        }


        // 保存到数据库
        Logininfo logininfo = new Logininfo();
        User user = new User();
        // 将密码加盐加密
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = MD5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setPassword(md5);
        user.setEmail(email);
        user.setSalt(salt);
        user.setUsername(email);
        user.setState(1);

        // 按照属性同名原则进行拷贝
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(false);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }


    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        // 一.校验  空值校验  1
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手机号不能为空哦！");
        }
        if (StringUtils.isEmpty(phoneCode)) {
            throw new BusinessException("手机验证码不能为空哦！");
        }
        if (StringUtils.isEmpty(pwd)) {
            throw new BusinessException("密码不能为空哦！");
        }
        if (StringUtils.isEmpty(rePwd)) {
            throw new BusinessException("确认密码不能为空哦！");
        }
        // 二.校验  密码是否相同   不需要数据库  2
        if (!pwd.equals(rePwd)) {
            throw new BusinessException("两次密码不一致哦！");
        }
        // 三.校验  短信验证码是否正确或验证码是否过期  需要操作数据库  3
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj == null) {
            throw new BusinessException("手机验证码过期了哦！");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)) { // redis中的手机验证码 与 用户输入的手机验证码
            throw new BusinessException("手机验证码错误了哦！");
        }

        // 四.添加到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 1.先添加t_logininfo 获取自增id
        logininfoMapper.save(logininfo);

        // 2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }


    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        // 生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码需要加密加盐
        String md5Pwd = MD5Utils.encrypByMd5(userDto.getPwd() + salt);
        // 设置盐值
        user.setSalt(salt);
        // 设置密码为加密加盐后的密码
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 按照属性同名原则进行拷贝
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1); // 用户
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void save(User user) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);
        // 保存user
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    @Override
    @Transactional
    public void del(Long id) {
        // 删除登录信息
        User user = userMapper.loadById(id);
        logininfoMapper.del(user.getLogininfoId());
        // 删除user信息
        super.del(id);
    }

    @Override
    @Transactional
    public void update(User user) {// 网上传递的user是没有logininfo_id
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);

        // 获取登录信息id
        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();

        // 创建logininfoId
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        // 将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo);// 5个数据是新的 ：用户名，邮箱，电话，盐值，密码


        logininfoMapper.update(logininfo);


    }
}
